/**
 *  @fileOverview  Config module for BDB.
 */

;(function() {

'use strict';

var _displayGroup = {
	groupName : '隐藏',
	page : 'stylePage',
	main : {
		'scrollbars' : {
			'type' : 'checkbox',
			'text' : '滚动条',
			'enable' : false,
			'selector' : 'body::-webkit-scrollbar'
		}, 'i_reply' : {
			'type' : 'checkbox',
			'text' : 'I 贴吧主页新提醒',
			'enable' : false,
			'selector' : '#newTopPanel~div[style]'
		}, 'i_cang' : {
			'type' : 'checkbox',
			'text' : 'I 贴吧主页收藏',
			'enable' : false,
			'selector' : '.favth_panel_home'
		}, 'popRightTop' : {
			'type' : 'checkbox',
			'text' : '右上角提醒',
			'enable' : false,
			'selector' : '.tb_message_tip_new'
		}, 'out_notice' : {
			'type' : 'checkbox',
			'text' : '贴吧公告',
			'enable' : false,
			'selector' : '#thread_list_table>tbody>tr:not([tid])'
		}, 'in_dingUp' : {
			'type' : 'checkbox',
			'text' : '一楼的顶按钮',
			'enable' : false,
			'selector' : '.p_ding_up'
		}, 'level_badge' : {
			'type' : 'checkbox',
			'text' : '贴吧等级牌',
			'enable' : false,
			'selector' : '.l_badge'
		}
	}
};

var ConfigContent = {
	// The following 3 proporties will be set later.
	allKeys : [ ],
	fKeys : [ ],
	bKeys : [ ],
	readOnly : [ ],
	defaultSetting : {
		main : { }, //// set later.
		formatVersion : 3
	},
	displayGroup : _displayGroup,
	fConfigGroup : [
		{
			groupName : '主题',
			page : 'stylePage',
			main : {
				'theme-style' : {
					'type' : 'checkbox',
					'text' : '使用BDB样式',
					'enable' : true
				}, 'theme-color' : {
					'type' : 'select',
					'text' : '色彩：',
					'options' : [
						{ value : 'BDB', text : 'BDB清新' },
						{ value : 'blue-white', text : '贴吧蓝白' },
						{ value : 'default', text : '官方默认' }
					]
				}
			}
		},
		_displayGroup,
		{
			groupName : '加强',
			page : 'functionPage',
			main : {
				'signSwitch' : {
					'type' : 'checkbox',
					'text' : '签名档开关',
					'enable' : true
				}, 'lastPageLink' : {
					'type' : 'checkbox',
					'text' : '尾页链接',
					'enable' : true
				}, 'nightMode' : {
					'type' : 'checkbox',
					'text' : '夜间模式开关',
					'enable' : false
				}, 'ipLookup' : {
					'type' : 'checkbox',
					'text' : 'ip党地理位置查询',
					'enable' : false
				}, 'floorLink' : {
					'type' : 'checkbox',
					'text' : '楼层链接',
					'enable' : false
				}, 'editorPlus' : {
					'type' : 'checkbox',
					'text' : '发贴辅助',
					'enable' : false
				}, 'decodePost' : {
					'type' : 'checkbox',
					'text' : '解析贴中的密语/UUcode',
					'enable' : true
				}
			}
		}, {
			groupName : '风格',
			page : 'functionPage',
			main : {
				'singleTab' : {
					'type' : 'checkbox',
					'text' : '单标签浏览',
					'enable' : false
				}, 'JKscroll' : {
					'type' : 'checkbox',
					'text' : 'Google风格浏览热键',
					'enable' : false
				}
			}
		}, {
			groupName : '快捷入口',
			page : 'functionPage',
			main : {
				'quickEntrance' : {
					'type' : 'checkbox',
					'text' : '恢复右上角快捷入口',
					'enable' : false
				}, 'quickEntranceEditor' : {
					'type' : 'textarea',
					'bindto' : 'quickEntrance'
				}
			}
		}, {
			groupName : '黑名单',
			page : 'blacklistPage',
			main : {
				'blacklist' : {
					'type' : 'checkbox',
					'text' : '启用黑名单功能',
					'enable' : false
				}, 'blacklistEditor' : {
					'type' : 'textarea',
					'bindto' : 'blacklist'
				}
			}
		}, {
			groupName : '自定义CSS',
			page : 'advancedPage',
			standAlone : true,
			main : {
				'userCSS' : {
					'type' : 'checkbox',
					'text' : '添加自定义CSS',
					'enable' : false
				}, 'userCSSEditor' : {
					'type' : 'textarea',
					'bindto' : 'userCSS'
				}
			}
		}
	],
	bConfigGroup : [
		{
			groupName : '网络',
			page : 'backgroundPage',
			main : {
				'refControl' : {
					'type' : 'checkbox',
					'text' : '反图片防盗链',
					'enable' : false
				}
			}
		}, {
			groupName : '右键菜单',
			page : 'backgroundPage',
			main : {
				'tb_search' : {
					'type' : 'checkbox',
					'text' : '百度贴吧搜索',
					'enable' : false
				}, 'pic_search' : {
					'type' : 'checkbox select',
					'text' : '图片搜索： ',
					'selectId' : 'image-search-engine',
					'options' : [
						{ value:'Baidu', text:'百度'},
						{ value:'Google', text:'Google'}
					],
					'enable' : false
				}, 'i_share' : {
					'type' : 'checkbox',
					'text' : '分享至 I 贴吧',
					'enable' : false
				}, 'du_cang' : {
					'type' : 'checkbox',
					'text' : '添加至百度搜藏',
					'enable' : false
				}
			}
		}
	]
}; // ${ ConfigContent } END


// Local shortcut.
var defaultGroup = Array.prototype.concat.call( [], ConfigContent.fConfigGroup, ConfigContent.bConfigGroup ),
	displayGroup = ConfigContent.displayGroup,
	defaultSetting = ConfigContent.defaultSetting;

var Config = {

	'bInit' : function() {
		'use strict';

		var groups = defaultGroup;
		for ( var i = 0, l = groups.length, group, table, frag; i < l; i++ ) {
			group = groups[i];
			if ( group['standAlone'] )
				continue;
			frag = document.createDocumentFragment();
			frag.appendChild( createConfigGroup( group ) );
			table = $( '#' + group.page + '>.displaytable' );
			table.append( frag );
		}

		Config.restore();
	},
	'fInit' : function( callback ) {
		'use strict';
		/** @const */
		var msg = {
				'hostname' : location.hostname,
				'ifModifiedSince' : +localStorage['__BDB_lastModified__'] || 0
		};

		$c.sendRequest( msg, callback );
	},
	'store' : function() {
		'use strict';

		var name,
			main = {},
			searchPage = $( '#searchPage' );

		for ( var tar, i = 0, l = ConfigContent.allKeys.length; i < l; i++ ) {
			name = ConfigContent.allKeys[i];
			if ( isReadOnly(name) ) {
				main[name] = defaultSetting['main'][name];
			} else {
				tar = $( '#' + name, searchPage );
				if ( tar.length === 0 )
					tar = $( '#' + name );
				if ( tar.length === 0 )
					continue;

				if ( tar.prop( 'type' ) === 'checkbox' )
					main[name] = tar.prop( 'checked' );
				else
					main[name] = encodeURI( tar.val().trim() );
			}
		}

		// Check if foreground or background setting changes.
		var oldMain = getConfigSettingMain();
		var fChange = false,
			bChange = false,
			key;
		for ( var i = ConfigContent.fKeys.length; i--; ) {
			key = ConfigContent.fKeys[i];
			if ( main[key] !== oldMain[key] ) {
				fChange = true;
				break;
			}
		}
		for ( var i = ConfigContent.bKeys.length; i--; ) {
			key = ConfigContent.bKeys[i];
			if ( main[key] !== oldMain[key] ) {
				bChange = true;
				break;
			}
		}

		if ( fChange === false && bChange === false ) {
			showSavingInfo();
			return;
		}

		main = btoa( JSON.stringify( main ) );
		var settingStr = JSON.stringify( {
				'formatVersion' : 3,
				'time' : $.now(),
				'main' : main
		} );
		localStorage['__BDB_configSetting__'] = settingStr;

		// Back up setting string in FileSystem.
		$.FileSys.write( 'BDB_configSetting.log', settingStr );

		if ( localStorage['__BDB_configSetting__'] === settingStr ) {
			if ( fChange )
				localStorage['__BDB_lastModified__'] = new Date().getTime();
			// We must not use native alert here,
			// which will interrupt FileSys.write();
			showSavingInfo();
		}

		$.fireEvent( 'setting-update', settingStr, true );
		if ( fChange )
			$.fireEvent( 'f-setting-update', settingStr, true );
		if ( bChange )
			$.fireEvent( 'b-setting-update', settingStr, true );

	},

	'restore' : function() {
		'use strict';

		var main = getConfigSettingMain(),
			name,
			_val,
			searched;
		for ( var i = ConfigContent.allKeys.length, elem; i--; ) {
			name = ConfigContent.allKeys[i];
			elem = $( '#' + name );
			searched = null;

			if ( !elem.length )
				return;

			if ( $( '#searchPage' ).length && $( '#' + name, $( '#searchPage' ) ).length )
				searched = $( '#' + name, $( '#searchPage' ) );
			if ( typeof main[name] !== 'undefined' ) {
				if ( elem.prop( 'type') === 'checkbox' ) {
					if ( main[name] === true )
						elem.prop( 'checked', true );
					else
						elem.prop( 'checked', false );
					if ( searched )
						searched.prop( 'checked', elem.prop( 'checked' ) );
				} else {
					_val = main[name];
					elem.val( decodeURI( _val ) );
					if ( searched )
						searched.val( elem.val() );
				}
			}

		} // End of loop.

	},

	'get' : function( name ) {
		'use strict';
		var main;
		if ( isReadOnly(  name  ) ) {
			main = getConfigSettingMain( true );
		} else {
			main = getConfigSettingMain();
		}

		if  ( typeof main[name] !== 'undefined' )
			return main[name];
		else
			return defaultSetting.main[name];
	},

	'getConfigSettingMain' : getConfigSettingMain
}; // ${ Config } END


// Generate ConfigContent;
ConfigContent.fKeys = collectKeys(ConfigContent.fConfigGroup);
ConfigContent.bKeys = collectKeys(ConfigContent.bConfigGroup);
ConfigContent.allKeys = ConfigContent.fKeys.concat(ConfigContent.bKeys);
function collectKeys(configGroup) {
	'use strict';
	var ret = [],
		groups = configGroup;
	for ( var i = 0, l = groups.length, main, key; i < l; i++ ) {
		main = groups[i].main;
		for ( key in main ) {
			ret.push( key );
			if ( typeof main[key]['selectId'] !== 'undefined' )
				ret.push( main[key]['selectId'] );
		}
	}
	return ret;
}
defaultSetting.main = (function()  {
	'use strict';
	var ret = {},
		groups = defaultGroup;
	for ( var i = 0, l = groups.length, main, key; i < l; i++ ) {
		main = groups[i].main;
		for ( key in main ) {
			switch ( main[key]['type'] ) {
				case 'checkbox':
					ret[key] = main[key]['enable'];
					break;
				case 'input':
				case 'textarea':
					ret[key] = '';
					break;
				case 'select':
					ret[key] = main[key]['options'][0]['value'];
					break;
				case 'checkbox select':
					ret[key] = main[key]['enable'];
					ret[main[key]['selectId']] = main[key]['options'][0]['value'];
					break;
			}
		}
	}
	return btoa( JSON.stringify( ret ) );
})();



// Return the config setting object.
$.addEventHandler( 'setting-update', function() {
	delete getConfigSettingMain.cache;
});
$.addEventHandler( 'setting-got-from-bgpage', function( ret ) {
	getConfigSettingMain.cache = ret.settingMain;
});
function getConfigSettingMain( defaultFlag ) {
	if ( defaultFlag ) {
		var ret = defaultSetting.main;
		ret = JSON.parse( atob( ret ) );
		return ret;
	}

	if ( typeof getConfigSettingMain.cache !== 'undefined' ) {
		return getConfigSettingMain.cache;
	}

	var setting;
	if ( typeof localStorage['__BDB_configSetting__'] !== 'undefined'  ) {
		setting = JSON.parse( localStorage['__BDB_configSetting__'] );
	} else {
		setting = defaultSetting;
	}

	var main = setting.main;
	main = JSON.parse( atob( main ) );

	getConfigSettingMain.cache = main;

	return main;
}

function createConfigGroup( gConfig ) {
	'use strict';
	if ( gConfig['standAlone'] )
		return null;

	var section = $ ('<section>' ).attr( 'class', 'bdb_config_section' );
	var h3 = $( '<h3>' ).text( gConfig.groupName ),
		div = $( '<div>' );

	if ( typeof gConfig['main'] !== 'undefined' ) {
		var main = gConfig.main,
			divHTML = '',
			text;
		for ( var id in main ) {
			switch ( main[id]['type'] ) {
				case 'checkbox':
					text = main[id]['text'];
					divHTML += '<div class=checkbox><label><input type=checkbox id=' + id + ' ' +
							( isReadOnly(id) ? ' disabled ' : ' ' ) +
							'><span>' + text + '</span></label></div>';
					break;
				case 'input':
					divHTML += '<div class=input><input id=' + id +
							( main[id]['bindto'] ? ' bindto=' + main[id]['bindto'] : ' ' ) + '></div>';
					break;
				case 'textarea':
					divHTML += '<div class=textarea><textarea id=' + id +
							( main[id]['bindto'] ? ' bindto=' + main[id]['bindto'] : ' ' ) + '></textarea></div>';
					break;
				case 'select':
					text = main[id]['text'];
					var selectHTML = '';
					main[id]['options'].forEach( function( op ) {
						selectHTML += '<option value="' + op['value'] + '">' + op['text'] + '</option>';
					});
					selectHTML = '<select id=' + id +'>' + selectHTML + '</select>';
					divHTML += '<div class="select"><label><span>' + text + '</span>' + selectHTML + '</label></div>';
					break;
				case 'checkbox select':
					text = main[id]['text'];
					var selectHTML = '';
					main[id]['options'].forEach( function( op ) {
						selectHTML += '<option value="' + op['value'] + '">' + op['text'] + '</option>';
					});
					selectHTML = '<select id=' + main[id]['selectId'] + ' bindto=' + id +'>' + selectHTML + '</select>';
					divHTML += '<div class="checkbox select"><label><input type=checkbox id=' + id + ' ' +
							( isReadOnly(id) ? ' disabled ' : ' ' ) +
							'><span>' + text + '</span></label>' + selectHTML + '</div>';
					break;
			}
		}
		div.html( divHTML );
	}
	section.append( h3, div );
	return section[0];
}


var switchesStorage = {
	signSwitch : 1,
	nightMode : 2,
	useUnicode : 4,

	/** Return 0 if not modified by BDB */
	getSwitch : function( key ) {
		'use strict';
		var switches = +localStorage['__BDB_switches__'] || 0;
		return switchesStorage[key] & switches;
	},

	switchKey : function( key ) {
		'use strict';
		var switches = +localStorage['__BDB_switches__'] || 0;
		switches ^= switchesStorage[key];
		localStorage['__BDB_switches__'] = switches;
		return switches;
	},

	getSwitchFunc : function( key ) {
		return function() {
			switchesStorage.switchKey( key );
		}
	}
};

function showSavingInfo() {
	'use strict';
	var saving_info = $( '.saving-info' );
	if ( saving_info.hasClass( 'saving-info-show' ) ) {
		saving_info.removeClass( 'saving-info-show' );
		clearTimeout( showSavingInfo.flashID );
	}
	setTimeout( function(){ saving_info.addClass( 'saving-info-show' ) }, 0 );
	showSavingInfo.flashID = setTimeout( function(){ saving_info.removeClass( 'saving-info-show' ) }, 2050 );
}

function isReadOnly( name ) {
	return ConfigContent.readOnly.indexOf( name ) > -1;
}

// Expose to global.
window.ConfigContent = ConfigContent;
window.switchesStorage = switchesStorage;
window.Config = Config;


})();


/**
 * Some constants of configs.
 */

/** @const */
var refOrigins = [
			"http://tieba.baidu.com/*",
			"http://imgsrc.baidu.com/*",
			"http://hiphotos.baidu.com/*",
			"http://*.ph.126.net/*",
			"http://*.bimg.126.net/*",
			"http://*.sinaimg.cn/*"
	];
/** @const */
var refPermissions = [ "webRequestBlocking" ];
/** @const */
var IPSearchAPIOrigins = [ "http://opendata.baidu.com/*" ];

